<template>
	<view class="container">
		<view class="uni-tab-title">
			<view class="line-box">
				<view
					:class="[
						'line-item',
						item.code == curTab ? 'active' : '',
					]"
					v-for="(item, key) in tabList"
					:key="key"
					@click="onClickLine(item)">
					{{ item.name }}
				</view>
			</view>
		</view>
		<view class="time-selector" v-if="curTab === 'timeCard'" >
			<view class="time-selector-title"> {{ dateValue }} 数据时间</view>
			<view style="text-align: center;">
				<picker 
					mode="date" 
					:value="dateValue"
					:end="maxDate"
					fields='month'
					@change="bindDateChange">
					<view class="uni-input-time">{{ dateValue }}</view>
				</picker>
			</view>
		</view>
		<view class="time-selector" v-if="curTab === 'ratio'">
		    <view class="time-selector-title"> {{ curTime }} 数据时间</view>
			<view
				v-if="timeList!=''" class="time-tabs" style="margin-top: 5px;">
				<view
					:class="[
						'time-tab',
						item.code == curData ? 'active' : '',
					]"
					v-for="(item, index) in timeList"
					:key="index"
					:data-time="item"
					@click="selectTime(item.code)"
				>
					{{ item.name }}
				</view>
			</view>
			<view v-if="curData == 'zidingyi'">
				<uni-datetime-picker type="year-month" fields="month" :end='endTime' :clear-icon="false" v-model="zdyTime" @change='timeChange' />
			</view>
		</view>
		<!-- 车间投用率 -->
		<view class="workshop-rate">
		    <view class="workshop-number">{{ shopValue }} <label style="font-size: 16px;">{{ shopUnit }}</label></view>
		    <view class="workshop-text">{{ shopTitle }}</view>
		</view>
		<kanban-ratio
			:utilData='areaData'
			:title="titleName.areaRatio"
			:unitValue='unitName.areaRatio'
			 v-if="curTab === 'ratio'"
		></kanban-ratio>
		<kanban-txratio
			:utilData='arealineData'
			:title="titleName.areaLineRatio"
		></kanban-txratio>
		<kanban-warn
			:equipmentData='equipmentData'
			:title="titleName.warn"
			 v-if="curTab === 'ratio'"
		></kanban-warn>
		<!-- 图表展示区域 -->
		<view class="chart-section">
		    <view class="chart-header">
		        <view class="chart-title">{{ titleName.arealineTend }}</view>
				<button class="select-button" @click="openModal()">
				    选择对比数据
				</button>
		        <view class="chart-time-selector" v-if="curTab === 'ratio'">
					<uni-datetime-picker v-model="rangeTime" :end='endTime' type="daterange" :clear-icon="false" @change='rangeChange'/>
		        </view>
		        <view class="chart-time-selector" v-if="curTab === 'timeCard'">
					<uni-datetime-picker v-model="rangetxyTime" :end='endTime' type="daterange" :clear-icon="false" @change='rangetxyChange'/>
		        </view>
		    </view>
				<!-- 自定义图例，用于切换显示的系列 -->
				<view class="custom-legend">
					<view class="legend-item" 
						  v-for="item in legendData" 
						  :key="item.index"
						  :class="{ 'active': activeIndexes.includes(item.index) }"
						  @click="toggleSeries(item.index)">
						<view class="legend-dot" :style="{ backgroundColor: item.color }"></view>
						<view class="legend-text">{{ item.name }}</view>
					</view>
				</view>
		    <view class="chart-container" v-if="echatrsData">
				<qiun-data-charts
					 :canvas-style="canvasStyle" 
				      type="line"
					  :canvas2d="true"
				      :opts="optsLine"
					  :reshow="isShow"
				      :chartData="lineData"
				    />
			</view>
			<view v-if="!echatrsData" style="margin-top: 5px; text-align: center;">
				暂无数据
			</view>
		</view>
		
		<!-- 设备详情弹窗 -->
		<uni-popup ref="popup" type="center" :mask-click="true">
		  <view class="popup-wrapper" style="width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center;background-color: #ffffff;">
		    <view class="popup-content" style="width: 100%; max-width: 100%;">
		      <view class="modal-header">
          <view class="modal-title">选择对比数据</view>
          <button class="close-btn" @click="closeModal()">×</button>
      </view>
		      <view class="modal-body">
		          <!-- 选择区域 -->
				<view class="select-area">
					<view class="area-title">选择项</view>
					 
				<!-- 动态生成选择项 -->
				<view class="condition-group" v-for="(group, groupIndex) in AllData" :key="groupIndex">
					<view class="group-title">{{ group.lineName }}</view>
						<view class="condition-items">
							<view 
							class="condition-item" 
							:class="{selected: isSelected(item.code, item.name)}" 
							@click="toggleSelection(item.code, item.name, item.codeName)"
							v-for="(item, itemIndex) in group.items" 
							:key="itemIndex"
						>
							{{ item.name }}
						</view>
						</view>
				</view> 
				 
			</view>
		          
		          <!-- 已选择区域 -->
          <view class="selected-area">
              <view class="area-title">已选择项</view>
              <view class="selected-items" id="selectedItems">
				        <view v-if="selectedItems.length === 0" class="empty-selected">暂无选择项</view>
				        <view v-else class="selected-tag" v-for="(item, index) in selectedItems" :key="index" @click="removeSelectedItem(item.code, item.name)">
								{{ item.codeName }}
							</view>
				    </view>
          </view>
		      </view>
		      <view class="modal-footer">
		          <button class="btn btn-cancel" @click="closeModal()">取消</button>
		          <button class="btn btn-confirm" @click="confirmSelection()">确定</button>
		      </view>
		    </view>
		  </view>
		</uni-popup>
	</view>
</template>

<script>
import { timestampFormatDate } from '../../../utils/FormatTime.js'
import { post, postForm } from '@/utils/request';
import { getUtilizationRateArea, getUtilizationRateLineArea, getFuncAnomaly, getUtilizationRateChart, getTYLArealist, getRYXArealist, tableStatistics, barChartAnalysis} from '@/api/check.js';
export default {
	name: '',
	data() {
        const date = new Date();
        const currentYear = date.getFullYear();
        const currentMonth = date.getMonth() + 1;
        // 格式化当前日期为YYYY-MM格式
        const currentDate = `${currentYear}-${currentMonth.toString().padStart(2, '0')}`;
		return {
			echatrsData: true,
			AllData: [],
			barData: true,
            // 存储不同tab的时间范围
            tabTimeRanges: {},
			canvasStyle: {
			    zIndex: 1,
			},
            dateValue: currentDate,
            maxDate: currentDate,
			curTime: Date.now(),
			curData: 'today',
			endTime: Date.now(),
			zdyTime: Date.now(),
			timeList: [
				{
					code: 'today',
					name: '今日'
				},
				{
					code: 'yesterday',
					name: '前一天'
				},
				{
					code: 'zidingyi',
					name: '自定义'
				}
			],
			timeData: {},
			areaData: [],
			arealineData: [],
			equipmentData: [],
			warnTitle: '',
			shopTitle: '',
			shopValue: '',
			shopUnit: '',
			titleName: {
				areaRatio: '',
				areaLineRatio: '',
				warn: '',
				arealineTend: '',
				dayTend: '',
			},
			unitName: {
				areaRatio: '',
				areaLineRatio: '',
				warn: '',
				arealineTend: '',
				jkTend: '',
			},
			curTab: 'ratio',
			tabList: [
				{
					name: '达标率',
					code: 'ratio'
				},
				{
					name: '天*项/月',
					code: 'timeCard'
				}
			],
			areaValue: '',
			areaList: [
				{
					value: '4',
					text: '加热',
				},
				{
					value: '2',
					text: '粗轧',
				},
				{
					value: '3',
					text: '精轧',
				},
				{
					value: '4',
					text: '卷取',
				},
			],
			activeIndexes: [0], // 默认激活加热炉曲线
			originalColors: ["#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc","#66ffff","#ffffbb","#ffb7dd","#096dd9","#ff8888","#b088ff","#ccff99","#ffbb00","#ff44aa","#33ffaa","#ccccff","#ff6666","#66ffcc","#ffcc66","#cc66ff","#66ccff","#ccff66","#ff66cc","#66ff99","#ff9966","#9966ff"], // 原始颜色
			rangeTime: [Date.now() - 30*24*3600*1000, Date.now()],
			rangetxyTime: [Date.now() - 30*24*3600*1000, Date.now()],
		
		barTime: [Date.now() - 7*24*3600*1000, Date.now()],
		// 添加临时快照变量
		tempSelectedItemsSnapshot: null,
			optsLine: {
			  color: [], // 初始为空，在mounted中设置
			  padding: [8, 20, 20, 10],
			  dataLabel: false,
			  dataPointShape: false,
			  enableScroll: false,
			  legend: {
			      show: false,
			  },
			  xAxis: {
			    disableGrid: true,
			    marginTop: 5,
			    scrollShow: false,
				padding: [0, 20], // 文字自身的上下左右留白 [!code focus]
				offset: 15,         // 轴线距离图表容器底部的距离 [!code focus]
				fontSize: 12,       // 文字大小（影响整体占位）
			    labelCount: 6, // [!code focus]
				gridEval: 5,
				boundaryGap: 'justify'  // 均匀分布模式
			  },
			  yAxis: {
			    gridType: "dash",
			    dashLength: 2
			  },
			  extra: {
			    line: {
			      type: "curve",
			      width: 2,
			      activeType: "hollow",
			    }
			  }
			},
			lineData: {},
			isShow: false,
			originalSeriesData: null,
			selectedItems: [{ code: '0', name: '车间', codeName: '车间' }], // 存储已选择的项，默认选中车间
			tylSelected: [{ code: '0', name: '车间', codeName: '车间' }],
			txySelected: [{ code: '0', name: '车间', codeName: '车间' }],
		};
	},
	
	watch: {
	},
	onLoad(option) {
	},
	onShow() {
		this.curTime = Date.now()
		this.zdyTime = Date.now() - 2*24*3600*1000
		this.curTime = timestampFormatDate(this.curTime, 'yyyy-MM-dd')
		this.zdyTime = timestampFormatDate(this.zdyTime, 'yyyy-MM-dd')
		let startBar = Date.now() - 7*24*3600*1000
		let start = Date.now() - 30*24*3600*1000
		let end = Date.now()
		this.rangeTime = [timestampFormatDate(start, 'yyyy-MM-dd'),timestampFormatDate(end, 'yyyy-MM-dd')]
		this.rangetxyTime = [timestampFormatDate(start, 'yyyy-MM-dd'),timestampFormatDate(end, 'yyyy-MM-dd')]
		this.getRatio()
		this.getWarn()
		this.getLine()
		this.querytylArea()
	},
	mounted() {
		// 在组件挂载后设置初始颜色
		this.updateChartColors();
	},
	computed: {
		// 获取图例数据
		legendData() {
			if (!this.lineData || !this.lineData.series) return [];
			return this.lineData.series.map((series, index) => {
				return {
					name: series.name,
					color: this.activeIndexes.includes(index) ? this.originalColors[index] : '#CCCCCC',
					index: index
				};
			});
		}
	},
	methods: {
		 bindDateChange: function(e) {
		    this.dateValue = e.detail.value
			this.queryMouth()
		},
		onClickLine(item) {
		this.curTab = item.code;
		if(this.curTab === 'ratio') {
			if(this.tylSelected.length > 0) {
				this.selectedItems = this.tylSelected
			} else {
				this.selectedItems = [{ code: '0', name: '车间', codeName: '车间' }];
			}
			this.echatrsData = true;
			this.getRatio();
			this.getWarn();
			this.getLine();
			this.querytylArea();
		} else {
			console.log('this.txySelected', this.txySelected)
			if(this.txySelected.length > 0) {
				this.selectedItems = this.txySelected
			} else {
				this.selectedItems = [{ code: '0', name: '车间', codeName: '车间' }];
			}
			this.echatrsData = true;
			this.queryMouth();
			this.getryxLine();
			this.queryryxArea();
		}
	},
		selectTime(time) {
			let timeData = ''
			if(time != 'zidingyi') {
				if(time == 'today') {
					timeData = Date.now()
					this.curTime = timestampFormatDate(timeData, 'yyyy-MM-dd')
				} else if(time == 'yesterday') {
					timeData = Date.now() - 1*24*3600*1000
					this.curTime = timestampFormatDate(timeData, 'yyyy-MM-dd')
				}
			} else {
				timeData = this.zdyTime
				this.curTime = timeData
				}
			this.curData = time
			this.getRatio()
			this.getWarn()
			//this.getLine()
		},
		async queryMouth() {
			uni.showLoading({
				title: '数据加载中！',
				mask: true,
			});
			const userInfor = uni.getStorageSync('userInfor');
			const dataParams = {
				queryDate: this.dateValue,
				version: 1,
				workshopId: 9
			}
			const res = await tableStatistics(dataParams);
			uni.hideLoading();
			let resData = res.data.data
			this.shopTitle = resData.title
			this.shopValue = resData.workshopValue
			this.shopUnit = resData.workshopUnit
			this.titleName.areaLineRatio = resData.title2
			this.arealineData = resData.listData
		},
		async queryryxArea() {
			let data = {
				version: 1
			}
			const res = await getRYXArealist(data);
			this.AllData = res.data.data
		},
		
		async querytylArea() {
			const userInfor = uni.getStorageSync('userInfor');
			const dataParams = {
				userId: userInfor.userId,
				moduleType: 'PRECISION'
			}
			const res = await getTYLArealist(dataParams);
			this.AllData = res.data.data
		},
		getServerData(res) {
		    this.barData = JSON.parse(JSON.stringify(res));
		},
		async getRatio() {
			uni.showLoading({
				title: '数据加载中！',
				mask: true,
			});
			const userInfor = uni.getStorageSync('userInfor');
			const dataParams = {
				userId: userInfor.userId,
				queryDate: this.curTime,
				moduleType: 'PRECISION'
			}
			const data1Params = {
				userId: userInfor.userId,
				queryDate: this.curTime,
				moduleType: 'PRECISION'
			}
			const res = await getUtilizationRateArea(dataParams);
			uni.hideLoading();
			let resData = res.data
			this.titleName.areaRatio = resData.title
			this.unitName.areaRatio = resData.unit
			this.areaData = resData.statisticsList
			const res1 = await getUtilizationRateLineArea(data1Params);
			uni.hideLoading();
			let res1Data = res1.data
			this.titleName.areaLineRatio = res1Data.title
			this.arealineData = res1Data.listData
			this.shopTitle = res1Data.workshopName
			this.shopValue = res1Data.workshopValue
			this.shopUnit = res1Data.workshopUnit
		},
		async getWarn() {
			const userInfor = uni.getStorageSync('userInfor');
			const dataParams = {
				userId: userInfor.userId,
				queryTime: this.curTime,
				moduleType: 'PRECISION'
			}
			const res = await getFuncAnomaly(dataParams);
			uni.hideLoading();
			this.titleName.warn = res.data.title
			let resData = res.data.data
			for(var i=0; i< resData.length; i++) {
				if(resData[i].count > 0) {
					resData[i].state = 'warning'
				} else {
					resData[i].state = 'normal'
				}
				if(resData[i].desc.length > 50) {
					let mid = resData[i].desc.slice(0,50)
					resData[i].desc = mid + '...'
				}
			}
			this.equipmentData = resData
		},
		async getLine() {
			const userInfor = uni.getStorageSync('userInfor');
			const dataParams = {
				userId: userInfor.userId,
				startTime: this.rangeTime[0],
				endTime: this.rangeTime[1],
				scopeList: this.selectedItems,
				moduleType: 'PRECISION'
			}
			/* type: 'AREA_LINE',
			moduleType: 'PRECISION' */
			
			const res = await getUtilizationRateChart(dataParams);
			let resData = res.data
			this.titleName.arealineTend = resData.title
			let dataLength = res.data.categories.length
			if(dataLength > 10) {
				this.optsLine.xAxis.labelCount = 4
			} else if(dataLength == 10) {
				this.optsLine.xAxis.labelCount = 3
			} else {
				this.optsLine.xAxis.labelCount = 6
			}
			let linedata = {
				categories: resData.categories,
				series: resData.series
			}
			// 使用series的长度来初始化activeIndexes，确保所有曲线都显示
			if (resData.series && resData.series.length > 0) {
				this.activeIndexes = Array.from({length: resData.series.length}, (_, i) => i);
				// 更新图表颜色以反映所有系列都处于激活状态
				this.updateChartColors();
			}
			this.confirmDateRange(linedata)
			return Promise.resolve(); // 添加这行以支持Promise链式调用
		},
		async getryxLine() {
			let scopeList = []
			for(var i= 0; i<this.selectedItems.length; i++) {
				scopeList[i] = {}
				scopeList[i].type = this.selectedItems[i].code
			}
			const userInfor = uni.getStorageSync('userInfor');
			const dataParams = {
				userId: userInfor.userId,
				version: 1,
				startDate: this.rangetxyTime[0],
				endDate: this.rangetxyTime[1],
				scopeList: scopeList,
				workshopId: 9
			}
			/* type: 'AREA_LINE',
			moduleType: 'PRECISION' */
			
			const res = await barChartAnalysis(dataParams);
			let resData = res.data
			this.titleName.arealineTend = resData.title
			let dataLength = res.data.categories.length
			if(dataLength > 10) {
				this.optsLine.xAxis.labelCount = 4
			} else if(dataLength == 10) {
				this.optsLine.xAxis.labelCount = 3
			} else {
				this.optsLine.xAxis.labelCount = 6
			}
			let linedata = {
				categories: resData.categories,
				series: resData.series
			}
			// 使用series的长度来初始化activeIndexes，确保所有曲线都显示
			if (resData.series && resData.series.length > 0) {
				this.activeIndexes = Array.from({length: resData.series.length}, (_, i) => i);
				// 更新图表颜色以反映所有系列都处于激活状态
				this.updateChartColors();
			}
			this.confirmDateRange(linedata)
			return Promise.resolve(); // 添加这行以支持Promise链式调用
		},
		timeChange() {
			this.curTime = this.zdyTime
			this.getRatio()
			this.getWarn()
		},
		rangeChange() {
            
            this.originalSeriesData = null
            this.getLine()
        },
		
		rangetxyChange() {
		    
		    this.originalSeriesData = null
		    this.getryxLine()
		},
		openModal() {
			// 创建当前选择项的深拷贝快照
			this.tempSelectedItemsSnapshot = JSON.parse(JSON.stringify(this.selectedItems));
			this.$refs.popup.open();
		},
		
		closeModal() {
			// 优先使用快照恢复数据
			if (this.tempSelectedItemsSnapshot) {
				this.selectedItems = JSON.parse(JSON.stringify(this.tempSelectedItemsSnapshot));
				this.tempSelectedItemsSnapshot = null;
			} else {
				// 如果快照不存在（不应该发生），则根据当前标签使用对应的已确认数据
				if(this.curTab === 'ratio') {
					this.selectedItems = this.tylSelected;
				} else {
					this.selectedItems = this.txySelected;
				}
			}
			this.$refs.popup.close();
		},
		barChange() {
		},
		areaChange() {
		},
		change() {},
		confirmDateRange(res) {
		    // 确保所有系列都显示
		    this.lineData = JSON.parse(JSON.stringify(res));
			
		    // 强制更新图表的两步策略
		    this.isShow = false;
			
		    // 使用$nextTick确保DOM更新
		    this.$nextTick(() => {
		        // 重置后再显示，强制图表重绘
		        this.isShow = true;
		    
		        // 为确保图表完全渲染，可以再添加一个$nextTick
		        this.$nextTick(() => {
		            // 再次使用$set强制更新
		            if (this.lineData && this.lineData.series) {
		                this.$set(this, 'lineData', {...this.lineData});
		            }
		        });
		    });
		},
		toggleSelection(code, name, codeName) {
				// 检查该项是否已被选择
				const index = this.selectedItems.findIndex(item => item.code === code && item.name === name);
				if (index > -1) {
					// 如果已选择，则移除
					this.selectedItems.splice(index, 1);
				} else {
					this.selectedItems.push({ code, name, codeName });
				}
				console.log('this.selectedItems', this.selectedItems)
			},
			
			
			// 从已选择项中移除指定项
			removeSelectedItem(code, name) {
			    // 修复：只删除非"车间"的选项
			        const index = this.selectedItems.findIndex(item => item.code === code && item.name === name);
			        if (index > -1) {
			            this.selectedItems.splice(index, 1);
			        }
			},
		
		isSelected(code, name) {
			// 检查该项是否已被选择，用于动态添加selected类
			return this.selectedItems.some(item => item.code === code && item.name === name);
		},
		
		async confirmSelection() {
		    // 修复：确认选择时去重
		    // 创建一个新的去重后的数组
		    const uniqueItems = [];
		    const seen = new Set();
			
		    this.selectedItems.forEach(item => {
		        const key = `${item.code}-${item.name}`;
		        if (!seen.has(key)) {
		            seen.add(key);
		            uniqueItems.push(item);
		        }
		    });
			
		    // 更新selectedItems
		    this.selectedItems = uniqueItems;
			
			if(this.selectedItems.length > 0) {
			    this.originalSeriesData = null;
			    this.echatrsData = true;
			    // 等待数据加载完成
			    if(this.curTab === 'ratio') {
					this.tylSelected = JSON.parse(JSON.stringify(this.selectedItems))
			        await this.getLine();
			    } else {
					this.txySelected = JSON.parse(JSON.stringify(this.selectedItems))
			        await this.getryxLine();
			    }
			} else {
			    this.lineData = {};
			    this.echatrsData = false;
			}
			
			// 确认选择后的处理逻辑
			console.log('已选择的项:', this.selectedItems);
			// 处理完成后关闭弹窗
			this.$refs.popup.close();
		},
		showEquipmentDetail(data) {
		    const details = data.subItem || [];
		    this.modalTitle = data.name + " 详细异常";
		    this.detailList = details;
			this.$refs.popup.open();
		  },
		  
		  // 切换显示的系列
		  toggleSeries(index) {
		  	// 使用Vue响应式赋值方式
		  	const newActiveIndexes = [...this.activeIndexes];
		  	const indexPos = newActiveIndexes.indexOf(index);
		  	if (indexPos === -1) {
		  		// 如果不在数组中，添加进去（同时显示）
		  		newActiveIndexes.push(index);
		  	} else {
		  		// 如果已在数组中，从数组中移除（不再显示）
		  		newActiveIndexes.splice(indexPos, 1);
		  		// 确保至少保留加热炉曲线（索引0）
		  		if (newActiveIndexes.length === 0) {
		  			newActiveIndexes.push(0);
		  		}
		  	}
		  	this.activeIndexes = newActiveIndexes;
		  	// 更新图表颜色
		  	this.updateChartColors();
		  	// 处理曲线的显示和隐藏
		  	this.handleSeriesVisibility();
		  	if (!this.lineData || !this.lineData.series) return;
		  	
		  	// 保存原始数据的副本，以便恢复
		  	if (!this.originalSeriesData) {
		  		this.originalSeriesData = JSON.parse(JSON.stringify(this.lineData.series));
		  	}
		  	
		  	// 深拷贝原始数据，避免直接修改
		  	const seriesCopy = JSON.parse(JSON.stringify(this.originalSeriesData));
		  	
		  	// 根据activeIndexes控制每个系列的显示/隐藏
		  	this.lineData.series = seriesCopy.map((series, index) => {
		  		if (this.activeIndexes.includes(index)) {
		  			// 显示的系列，保持原始数据
		  			return series;
		  		} else {
		  			// 隐藏的系列，将数据设置为空数组
		  			return {
		  				...series,
		  				data: []
		  			};
		  		}
		  	});
		  },
		  // 更新图表颜色
		  updateChartColors() {
		  	this.optsLine.color = this.originalColors.map((color, index) => {
		  		return this.activeIndexes.includes(index) ? color : '#CCCCCC';
		  	});
		  },
		  // 处理曲线的显示和隐藏
		handleSeriesVisibility() {
		  	if (!this.lineData || !this.lineData.series) return;
		  	
		  	// 保存原始数据的副本，以便恢复
		  	if (!this.originalSeriesData) {
		  		this.originalSeriesData = JSON.parse(JSON.stringify(this.lineData.series));
		  	}
		  	
		  	// 深拷贝原始数据，避免直接修改
		  	const seriesCopy = JSON.parse(JSON.stringify(this.originalSeriesData));
		  	
		  	// 根据activeIndexes控制每个系列的显示/隐藏
		  	this.lineData.series = seriesCopy.map((series, index) => {
		  		if (this.activeIndexes.includes(index)) {
		  			// 显示的系列，保持原始数据
		  			return series;
		  		} else {
		  			// 隐藏的系列，将数据设置为空数组
		  			return {
		  				...series,
		  				data: []
		  			};
		  		}
		  	});
		  	
		  	// 使用更稳定的方式更新图表，避免组件销毁重建
		  	this.$set(this, 'lineData', {...this.lineData});
		},
	},
}
</script>
<style>
	.uni-stat__select {
	    display: flex;
	    align-items: center;
	    width: 100%;
	    flex: 1;
		height: 35px;
	    box-sizing: border-box;
		border: 1px solid #e5e5e5;
		border-radius: 4px;
	}
</style>
<style scoped lang="scss">
	.container {
		padding: 12px;
	}
	.uni-tab-title {
		border-bottom: 1px solid rgba(237, 237, 237, 0.9);
	}
	.line-box {
		display: flex;
		.line-item {
			text-align: center;
			padding: 10px;
			border-radius: 1px;
			background: #fff;
			z-index: 1;
			flex: calc(25% - 8px);
	
			&.active {
				background: #ffffff;
				color: #4055e6;
				border-bottom: 2px solid #4055e6;
			}
		}
	}
	/* 时间筛选器 */
	       .time-selector {
	           background: white;
	           border-radius: 12px;
	           padding: 16px;
	           margin-bottom: 16px;
			   margin-top: 10px;
	           box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
	           border: 1px solid #f0f0f0;
	       }
	
	       .time-selector-title {
	           font-size: 14px;
	           font-weight: 600;
	           color: #262626;
	           margin-bottom: 12px;
	           display: flex;
	           align-items: center;
	       }
	
	       .time-selector-title::before {
	           content: '📅';
	           margin-right: 8px;
	           font-size: 16px;
	       }
	       .uni-input-time {
			   border: 1px solid #e5e5e5;
			   border-radius: 4px;
			   line-height: 35px;
		   }
	       .time-tabs {
	           display: flex;
	           background: #f5f5f5;
	           border-radius: 8px;
	           padding: 4px;
	           gap: 4px;
	       }
	
	       .time-tab {
	           flex: 1;
	           text-align: center;
	           padding: 8px 12px;
	           border-radius: 6px;
	           font-size: 13px;
	           font-weight: 500;
	           color: #8c8c8c;
	           transition: all 0.2s ease;
	           cursor: pointer;
	       }
	
	       .time-tab:active {
	           transform: scale(0.98);
	       }
	
	       .time-tab.active {
			   background: #1890ff;
			   color: white;
			   box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
			 }
		/* 车间投用率 */
		.workshop-rate {
		    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
		    border-radius: 12px;
		    padding: 10px;
		    text-align: center;
		    color: white;
		    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
		}
		
		.workshop-number {
		    font-size: 30px;
		    font-weight: 700;
		    margin-bottom: 2px;
		    color: white;
		}
		
		.workshop-text {
		    font-size: 13px;
		    color: white;
		    opacity: 0.9;
		}
		
		/* 自定义图例样式 */
		.custom-legend {
			display: flex;
			flex-wrap: wrap;
			background: white;
		}
		.legend-item {
			display: flex;
			align-items: center;
			cursor: pointer;
			padding: 4px 8px;
			border-radius: 4px;
			transition: all 0.2s;
		}
		.legend-item:active {
			background: #f5f5f5;
		}
		.legend-dot {
			width: 12px;
			height: 12px;
			border-radius: 50%;
			margin-right: 6px;
		}
		.legend-text {
			font-size: 12px;
			color: #333;
		}
		/* 图表区域 */
        .chart-section {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
        }
		
		.chart-header {
			margin-bottom: 5px;
		}
		
		.chart-title {
		    font-size: 16px;
		    font-weight: 600;
		    color: #333;
		    margin-bottom: 16px;
		}
		
		.chart-title::before {
		    content: '📈';
		    margin-right: 8px;
		}
		
		.chart-time-selector {
		    align-items: center;
		    gap: 8px;
			margin-top: 2px;
		}
		
		.date-range-picker {
		    display: flex;
		    align-items: center;
		    gap: 4px;
		    background: #f5f5f5;
		    border-radius: 6px;
		    padding: 4px 8px;
		    font-size: 14px;
		    color: #666;
		}
		
		.date-input {
		    border: none;
		    background: transparent;
		    font-size: 11px;
		    color: #666;
		    width: 80px;
		    text-align: center;
		    outline: none;
		}
		
		.date-separator {
		    color: #999;
		    margin: 0 2px;
		}
		
		.date-confirm-btn {
		    background: #1890ff;
		    color: white;
		    border: none;
		    border-radius: 4px;
		    padding: 2px 6px;
		    font-size: 10px;
		    cursor: pointer;
		    margin-left: 4px;
		    transition: all 0.2s ease;
		}
		
		.date-confirm-btn:active {
		    transform: scale(0.95);
		    background: #096dd9;
		}
		
		.chart-container {
		    height: 250px;
		}
		
		/* 选择按钮 */
		.select-button {
		    width: 100%;
		    padding: 2px 12px;
			margin-top: 10px;
			margin-bottom: 10px;
		    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
		    color: white;
		    border: none;
		    border-radius: 8px;
		    font-size: 14px;
		    font-weight: 600;
		    cursor: pointer;
		    box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);
		}
		/* 弹框 */
		.popup-wrapper {
		  position: fixed;
		  width: 100vw;
		  height: 100vh;
		  display: flex;
		  justify-content: center;
		  align-items: center;
		  background-color: #ffffff;
		  top: 0;
		  left: 0;
		  z-index: 9999;
		}
		
		.popup-content {
		  width: 100% !important;
		  max-width: 100% !important;
		  height: 100vh;
		  margin: 0;
		  border-radius: 0;
		  display: flex;
		  flex-direction: column;
		}
		.modal-header {
		    padding: 14px 20px;
		    border-bottom: 1px solid #f0f0f0;
		    display: flex;
		    justify-content: center;
		    align-items: center;
		    position: relative;
		}
		
		.modal-title {
		    font-weight: 600;
		    color: #333;
		}
		
		.close-btn {
		    width: 22px;
		    height: 22px;
		    border: none;
		    background: #f5f5f5;
		    border-radius: 50%;
		    cursor: pointer;
		    display: flex;
		    align-items: center;
		    justify-content: center;
		    color: #666;
		    position: absolute;
		    right: 20px;
		}
		
		.modal-body {
		    flex: 1;
		    overflow-y: auto;
		    padding: 14px 14px;
		    -webkit-overflow-scrolling: touch; /* 为iOS设备启用平滑滚动 */
		}
		
		.select-area {
		    margin-bottom: 14px;
		}
		
		.area-title {
		    font-weight: 500;
		    color: #333;
		    margin-bottom: 10px;
		}
		
		.condition-group {
		    margin-bottom: 12px;
		}
		
		.group-title {
		    font-weight: 500;
		    color: #333;
		    margin-bottom: 6px;
		    padding-left: 8px;
		    border-left: 3px solid #1890ff;
		}
		
		.condition-items {
		    display: grid;
		    grid-template-columns: 1fr 1fr 1fr;
		    gap: 5px;
		}
		
		.condition-item {
		    padding: 4px 4px;
		    background: #f8f9fa;
		    border: 1px solid #e9ecef;
		    border-radius: 5px;
		    color: #333;
		    cursor: pointer;
		    text-align: center;
		    font-weight: 500;
		    min-height: 30px;
		    display: flex;
		    align-items: center;
		    justify-content: center;
		}
		
		.condition-item:hover {
		    background: #e6f7ff;
		    border-color: #91d5ff;
		}
		
		.condition-item.selected {
		    background: #1890ff;
		    border-color: #1890ff;
		    color: white;
		    font-weight: 600;
		}
		
		.selected-area {
		    border-top: 1px solid #f0f0f0;
		    padding-top: 14px;
		}
		
		.selected-items {
		    display: flex;
		    flex-wrap: wrap;
		    gap: 5px;
		    min-height: 35px;
		}
		
		.selected-tag {
		    display: flex;
		    align-items: center;
		    gap: 3px;
		    padding: 5px 8px;
		    background: #e6f7ff;
		    color: #1890ff;
		    border-radius: 5px;
		    font-weight: 500;
		    cursor: pointer;
		    transition: background 0.2s;
		    min-height: 24px;
		}
		
		.selected-tag:hover {
		    background: #bae7ff;
		}
		
		.empty-selected {
		    color: #999;
		    text-align: center;
		    padding: 10px;
		}
		
		.modal-footer {
		    padding: 10px 20px;
		    border-top: 1px solid #f0f0f0;
		    display: flex;
		    gap: 10px;
		}
		
		.btn {
		    flex: 1;
		    border: none;
		    border-radius: 5px;
		    font-weight: 500;
		    cursor: pointer;
		}
		
		.btn-cancel {
		    background: #f5f5f5;
		    color: #666;
		}
		
		.btn-confirm {
		    background: #1890ff;
		    color: white;
		}
</style>
